package com.up.upzl.biz.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.up.upzl.biz.domain.SysApp;
import com.up.upzl.biz.service.SysRoleAppService;

import lombok.Getter;
import lombok.Setter;

/**
 * 系统用户控制器
 * 
 * @author nathan
 *
 */
@Controller
@RequestMapping("sysRoleApp")
public class SysRoleAppController {

	@Autowired
	private SysRoleAppService sysRoleAppService;

	@GetMapping("list")
	public String roleAppList(Model model) {
		model.addAttribute("roles", sysRoleAppService.findAllRoleList());
		return "sysRoleApp/list";
	}

	@GetMapping("getApps")
	public @ResponseBody List<SysRoleAppTreeNode> getRoleApps(Long roleID) {
		List<SysApp> allApp = sysRoleAppService.findAllApps();
		List<SysRoleAppTreeNode> treeNode = new ArrayList<>();
		List<SysApp> roleApps = sysRoleAppService.findRoleApps(roleID);
		for (SysApp sysApp : allApp) {
			SysRoleAppTreeNode node = new SysRoleAppTreeNode();
			node.setPId(sysApp.getParentId() == null ? 0 : sysApp.getParentId());
			node.setId(sysApp.getId());
			node.setName(sysApp.getAppName());
			node.setOpen(true);
			if (roleApps.contains(sysApp)) {
				node.setChecked(true);
			} else {
				node.setChecked(false);
			}
			treeNode.add(node);
		}
		return treeNode;
	}

	@PostMapping("saveApps")
	public @ResponseBody boolean saveRoleApp(Long roleID, Long[] appIDs) {
		sysRoleAppService.saveRoleApp(roleID, appIDs);
		return true;
	}

}

@Getter
@Setter
class SysRoleAppTreeNode {
	private long id;
	private long pId;
	private String name;
	private boolean checked;
	private boolean open;
}
